using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 负责敌人生成规则
/// </summary>
public class EnemySpawner : MonoBehaviour
{
    [Header("敌人生成速度和范围")]
    [Tooltip("生成速度")]
    public float spawnRate = 2f;
    [Tooltip("生成范围")]
    public float spawnOffset = 2f; 
    
    [Header("敌人列表和世界坐标")]
    public List<GameObject> enemies = new List<GameObject>();
    private Vector2 screenBounds;
    
    /// <summary>
    /// 计算屏幕边界调用敌人生成方法
    /// </summary>
    void Start()
    {
        // 计算屏幕边界的世界坐标
        // new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z) 是屏幕右上角的像素坐标
        // Camera.main.ScreenToWorldPoint() 将其转换为世界坐标
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

        // 每隔spawnRate秒调用一次SpawnEnemy
        InvokeRepeating("SpawnEnemy", 0f, spawnRate); 
    }

    /// <summary>
    /// 敌人生成规则
    /// </summary>
    void SpawnEnemy()
    {
        // 获取一个随机的生成位置
        Vector2 spawnPosition = GetRandomSpawnPosition();
        //生成敌人预制体(先生成第一个)
        Instantiate(enemies[0], spawnPosition, Quaternion.identity);
    }
    
    /// <summary>
    /// 敌人生成位置
    /// </summary>
    private Vector2 GetRandomSpawnPosition()
    {
        Vector2 spawnPos = Vector2.zero;

        // 随机选择一个生成边 (0=上, 1=下, 2=左, 3=右)
        int side = Random.Range(0, 4);

        switch (side)
        {
            // Case 0: 在屏幕上方生成
            case 0:
                spawnPos.x = Random.Range(-screenBounds.x, screenBounds.x);
                spawnPos.y = screenBounds.y + spawnOffset;
                break;
            
            // Case 1: 在屏幕下方生成
            case 1:
                spawnPos.x = Random.Range(-screenBounds.x, screenBounds.x);
                spawnPos.y = -screenBounds.y - spawnOffset;
                break;

            // Case 2: 在屏幕左侧生成
            case 2:
                spawnPos.x = -screenBounds.x - spawnOffset;
                spawnPos.y = Random.Range(-screenBounds.y, screenBounds.y);
                break;
            
            // Case 3: 在屏幕右侧生成
            case 3:
                spawnPos.x = screenBounds.x + spawnOffset;
                spawnPos.y = Random.Range(-screenBounds.y, screenBounds.y);
                break;
        }

        return spawnPos;
    }

    /// <summary>
    /// 取消所有对此脚本的Invoke调用
    /// </summary>
    public void StopSpawning()
    {
        CancelInvoke();
    }
}
